<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
  <th:block th:insert="~{include :: header('Group list')}" />
  <th:block th:insert="~{include :: bootstrap-editable-css}" />
  <th:block th:insert="~{include :: select2-css}" />
</head>
<body class="gray-bg">

  <div class="container-div">
    <div class="row">
      <div class="col-sm-12 search-collapse">
        <form id="form-mg-group">
          <div class="select-list">
            <ul>
              <li>
                <label>分组名称：</label>
                <select class="form-control" name="groups">
                  <option value=""></option>
                </select>
              </li>
              <li>
                <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i class="fa fa-search"></i>&nbsp;搜索</a>
                <a class="btn btn-warning btn-rounded btn-sm" onclick="resetForm()"><i class="fa fa-refresh"></i>&nbsp;重置</a>
              </li>
            </ul>
          </div>
        </form>
      </div>

      <div class="btn-group-sm" id="toolbar" role="group">
        <a class="btn btn-success" onclick="add()" shiro:hasPermission="disjob:mggroup:operate">
          <i class="fa fa-plus"></i> 新增分组
        </a>
      </div>

      <div class="col-sm-12 select-table table-striped">
        <table id="bootstrap-table"></table>
      </div>
    </div>
  </div>

  <th:block th:insert="~{include :: footer}" />
  <th:block th:insert="~{include :: bootstrap-table-fixed-columns-js}" />
  <th:block th:insert="~{include :: bootstrap-table-editable-js}" />
  <th:block th:insert="~{include :: select2-js}" />

  <script th:inline="javascript">
    const operateFlag = [[${@permission.hasPermi('disjob:mggroup:operate')}]];
    const prefix = ctx + "disjob/mggroup";

    $(function () {
      const options = {
        url: prefix + "/list",
        createUrl: prefix + "/add",
        removeUrl: prefix + "/remove",
        fixedColumns: true,
        fixedNumber: 2,
        onEditableSave: updateOwnUser,
        rememberSelected: true,
        modalName: "分组",
        columns: [{
          field: 'group',
          title: '分组名称',
          formatter: function (value, row, index) {
            return '<a href="javascript:void(0)" onclick="workers(\'' + value + '\')">' + value + '</a>';
          }
        },
        {
          field: 'ownUser',
          title: '负责人',
          editable: {
            type: 'text',
            validate: function(value) {
              if (!value || !value.trim()) {
                return '不能为空';
              }
              if (value.length > 36) {
                return '不能超过36个字符';
              }
            }
          }
        },
        {
          field: 'updatedBy',
          title: '更新人'
        },
        {
          field: 'updatedAt',
          title: '更新时间'
        },
        {
          field: 'createdBy',
          title: '创建人'
        },
        {
          field: 'createdAt',
          title: '创建时间'
        },
        {
          title: '操作',
          align: 'center',
          formatter: function (value, row, index) {
            if (![[${@permission.isPermitted('disjob:mggroup:operate')}]]) {
              return '';
            }
            const actions = [];
            actions.push("<a class='btn btn-danger btn-rounded btn-xs " + operateFlag + "' href='javascript:void(0)' onclick='remove(&quot;" + row.group + "&quot;)'><i class='fa fa-trash'></i> 删除</a> ");
            actions.push("<a class='btn btn-success btn-rounded btn-xs " + operateFlag + "' href='javascript:void(0)' onclick='token(&quot;" + row.group + "&quot;)'><i class='fa fa-cogs'></i> 令牌</a> ");
            return '<a tabindex="0" class="btn btn-info btn-rounded btn-xs" role="button" data-container="body" data-placement="left" data-toggle="popover" data-html="true" data-trigger="hover" data-content="' + actions.join('') + '"><i class="fa fa-chevron-circle-right"></i> 操作</a>';
          }
        }]
      };
      $.table.init(options);

      // ---------------------------------select2
      $("select[name='groups']").select2({
        ajax: {
          url: prefix + "/search_group",
          type: "get",
          dataType: 'json',
          delay: 300,
          cache: true,
          data: function (params) {
            // {"term": "str", "_type": "query"}
            return {"term": params.term};
          },
          processResults: function (resp) {
            return {results: resp.data };
          }
        },
        placeholder: '请选择',
        minimumInputLength: 1
      });

    });

    function resetForm() {
      $.form.reset();
      const elem = $("select[name='groups']");
      elem.val(elem.val()).trigger("change");
    }

    function add() {
      $.modal.open("新增" + table.options.modalName, $.operate.addUrl(), '460', '240');
    }

    function remove(group) {
      $.modal.confirm("确定删除分组'" + group + "'吗？", function() {
        $.operate.post(table.options.removeUrl, { "group": group });
      });
    }

    function token(group) {
      const url = prefix + '/token?group=' + group;
      $.modal.open("令牌管理", url, '590', '345', null, ['复制', '关闭']);
    }

    function workers(group) {
      $.modal.popupRight(group, prefix + "/worker?group=" + group);
    }

    function updateOwnUser(field, row, rowIndex, oldValue) {
      if (field !== "ownUser") {
        row[field] = oldValue;
        $.modal.msgError("只能更新['ownUser']字段");
        return;
      }
      const newValue = row[field].trim();
      if (newValue.includes(",")) {
        row[field] = oldValue;
        $.modal.msgError("cannot contains char ','");
        return;
      }
      if (oldValue === newValue) {
        // reset to oldValue(none left or right blank)
        row[field] = oldValue;
        return;
      }
      const params = { "group": row.group, "ownUser": newValue };
      $.operate.post(prefix + "/update_own_user", params, function (result) {
        row[field] = (result.code === 0) ? newValue : oldValue;
      }, false);
    }
  </script>

</body>
</html>
